package device;

import base.UsersBaseInterface;
import device.callbacks.VerifyOnce;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import java.util.HashMap;

// 嵌入式设备抽象
public class Embedded extends Device {
    private static final Logger logger = LoggerFactory.getLogger(Embedded.class);
    private String previousBalance = "";
    public Embedded(SocketChannel socketChannel, UsersBaseInterface users) {
        super(socketChannel, users);
    }

    @Override
    public boolean subscribe(Device targetDevice, VerifyOnce verify) {
        super.subscribe(targetDevice);
        return true;
    }

    @Override
    public void update(HashMap<String, String> msgsSet) throws IOException {
        Collection<String> keySet = msgsSet.keySet();
        for (String key : keySet) {
            String msgValue = msgsSet.get(key);
            if (msgValue != null) {
                String value = keys.get(key);
                if (value != null && !msgValue.equals(value)) {
                    keys.replace(key, msgValue);
                    updateFlag = true;
                }
            }
        }

        String logoutControl = msgsSet.get("logout");
        if (logoutControl != null) {
            logger.info("用户 %s 在充电桩设备 id=%s 上退出登陆".formatted(userNameBundle, deviceID));
            /* 将退出登陆消息转发给订阅者 */
            ByteBuffer message = ByteBuffer.wrap("logout=y".getBytes());
            for (Device dev : subscribeSet) {
                dev.sendBuffer(message);
                /* 让用户终端取消对本充电桩设备的订阅 */
                dev.unSubscribe(this);
            }
            userNameBundle = null;
            updateFlag = false;
            return;
        }

        // 拦截 NFC 卡片的请求
        String nfcCardID = msgsSet.get("nfcid");
        if (nfcCardID != null) {
            logger.info("检测到用户 NFC 刷卡充电，id=%s".formatted(nfcCardID));
            float balance = users.queryUserBalance(nfcCardID);
            if (balance >= 0) {
                userNameBundle = nfcCardID;
                try {
                    logger.info("用户 id=%s，余额: %.2f".formatted(nfcCardID, balance));
                    simpleSend("a=%.2f".formatted(balance));
                } catch (IOException e) {
                    logger.error("向充电桩发送余额信息时，抛出异常。");
                }
            } else {
                userNameBundle = null;
                // 用户不存在的情况
                try {
                    logger.warn("不存在用户 id=%s".formatted(nfcCardID));
                    simpleSend("g=n,a=0.0,e=a");
                } catch (IOException e) {
                    logger.error("向充电桩发送信息时，抛出异常。");
                }
            }
            return;
        }

        if (userNameBundle != null) {
            String balance = keys.get("balance");
            try {
                if (balance != null && !balance.equals(previousBalance)) {
                    float b = Float.parseFloat(balance);
                    users.updateUserBalance(userNameBundle, b, true);
                    previousBalance = balance;
                }
            } catch (NumberFormatException _) {
            }
        }

    }
}
